/*
 * Created on 24/05/2005
 */
package util;

import java.awt.Canvas;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

/**
 * @author Diego Sanchez Gallo.
 */
public class TelaArcos extends JFrame {
    
    private static final int WINDOW_WIDTH = 800;
    private static final int WINDOW_HEIGHT = 600;
    
    private JComboBox comboBoxOrigem;
    private JComboBox comboBoxDestino;
    private JTextField textFieldCustos;
    
    private Canvas canvas;
    private Image imagem;

    private File xmlGrafo;
    
    public TelaArcos(File file, Image image, ArrayList nomesVertices) {
        super();
        
        xmlGrafo = file;
        imagem = image;
        
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
        setTitle("Gerador XML - Tela Arcos");
        
        canvas = new CanvasImagem();
        canvas.setSize(500, 500);
        
        JPanel panelDireito = new JPanel();
        panelDireito.setLayout(new BoxLayout(panelDireito, BoxLayout.Y_AXIS));
        
        JPanel panelDireitoCentro = new JPanel();
        panelDireitoCentro.setLayout(new BoxLayout(panelDireitoCentro, BoxLayout.Y_AXIS));
        JPanel panelDireitoCentroInfo = new JPanel();
        panelDireitoCentroInfo.setLayout(new GridLayout(3, 2));
        JLabel labelOrigem = new JLabel("Origem: ");
        comboBoxOrigem = new JComboBox();
        JLabel labelDestino = new JLabel("Destino: ");
        comboBoxDestino = new JComboBox();
        for (Iterator iter = nomesVertices.iterator(); iter.hasNext();) {
			String nome = (String) iter.next();
			comboBoxOrigem.addItem(nome);
			comboBoxDestino.addItem(nome);
		}
        JLabel labelCustos = new JLabel("Custos: ");
        textFieldCustos = new JTextField();
        panelDireitoCentroInfo.add(labelOrigem);
        panelDireitoCentroInfo.add(comboBoxOrigem);
        panelDireitoCentroInfo.add(labelDestino);
        panelDireitoCentroInfo.add(comboBoxDestino);
        panelDireitoCentroInfo.add(labelCustos);
        panelDireitoCentroInfo.add(textFieldCustos);
        panelDireitoCentroInfo.setBorder(BorderFactory.createEmptyBorder(20, 5, 20, 5));
//        panelDireitoCentroInfo.setMaximumSize(new Dimension(250, 100));
        JButton buttonAdicionarArco = new JButton("Adicionar");
        buttonAdicionarArco.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                adicionarArco();
            }
        });
        panelDireitoCentro.add(panelDireitoCentroInfo);
        panelDireitoCentro.add(buttonAdicionarArco);
        panelDireitoCentro.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("ARCOS"), BorderFactory.createEmptyBorder(15, 5, 25, 5)));
        
        JPanel panelDireitoInferior = new JPanel();
        panelDireitoInferior.setLayout(new BoxLayout(panelDireitoInferior, BoxLayout.X_AXIS));
        JButton buttonProximoGrafo = new JButton("Pr�x. grafo");
        buttonProximoGrafo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                proximoGrafo();
            }
        });
        JButton buttonConcluir = new JButton("Concluir");
        buttonConcluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                concluir();
            }
        });
        panelDireitoInferior.add(buttonProximoGrafo);
        panelDireitoInferior.add(buttonConcluir);
        panelDireitoInferior.setBorder(BorderFactory.createEmptyBorder(40, 10, 0, 10));
        
        panelDireito.add(panelDireitoCentro);
        panelDireito.add(panelDireitoInferior);
        panelDireito.setMaximumSize(new Dimension(250, 300));
        
        Container container = getContentPane();
        container.setLayout(new BoxLayout(container, BoxLayout.X_AXIS));
        container.add(canvas);
        container.add(panelDireito);
    }
    
    private void adicionarArco() {
        try {
            escreveTagArcoXML();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    private void proximoGrafo() {
        try {
            fechaTagGrafoXML();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        TelaVertices telaVertices = new TelaVertices();
        telaVertices.setXmlGrafo(xmlGrafo);
        telaVertices.pack();
        telaVertices.setVisible(true);
        this.dispose();
    }
    
    private void concluir() {
        try {
            fechaTagsXML();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        this.dispose();
    }
    
    private void escreveTagArcoXML() throws IOException {
        StringBuffer buffer = new StringBuffer();
        buffer.append("            <arco origem=\"");
        buffer.append((String) comboBoxOrigem.getSelectedItem());
        buffer.append("\" destino=\"");
        buffer.append((String) comboBoxDestino.getSelectedItem());
        buffer.append("\">\n");
        
        String custos = textFieldCustos.getText();
        String arrayCustos[] = custos.split(":"); //caracter separador dos custos
        for (int i = 0; i < arrayCustos.length; i++) {
            buffer.append("                <custo restricao=\"");
            buffer.append(i);
            buffer.append("\" valor=\"");
            buffer.append(arrayCustos[i]);
            buffer.append("\"/>\n");
        }
        
        buffer.append("            </arco>\n");

        FileOutputStream fos = new FileOutputStream(xmlGrafo, true);
        fos.write(buffer.toString().getBytes());
        fos.flush();
        fos.close();
    }
    
    private void fechaTagGrafoXML() throws IOException {
        StringBuffer buffer = new StringBuffer();
        buffer.append("        </arcos>\n");
        buffer.append("    </grafo>\n\n");
        
        FileOutputStream fos = new FileOutputStream(xmlGrafo, true);
        fos.write(buffer.toString().getBytes());
        fos.flush();
        fos.close();
    }
    
    private void fechaTagsXML() throws IOException {
        StringBuffer buffer = new StringBuffer();
        buffer.append("        </arcos>\n");
        buffer.append("    </grafo>\n\n");
        buffer.append("</estabelecimento>");
        
        FileOutputStream fos = new FileOutputStream(xmlGrafo, true);
        fos.write(buffer.toString().getBytes());
        fos.flush();
        fos.close();
    }
    
    public class CanvasImagem extends Canvas implements MouseListener, MouseMotionListener, MouseWheelListener {
        
    	double hmult = 1;
		int xprev = 0;
		int yprev = 0;
		int xpos = 0;
		int ypos = 0;
		
        public CanvasImagem () {
            addMouseListener(this);
            addMouseMotionListener(this);
            addMouseWheelListener(this);
        }
        
        public void paint(Graphics graphics) {
            if (imagem != null) {
            	graphics.drawImage(imagem, xpos, ypos,(int)(imagem.getWidth(this) * hmult),  (int)(imagem.getHeight(this) * hmult), null);
            }
        }

        /* (non-Javadoc)
         * @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent)
         */
        public void mouseClicked(MouseEvent e) {
			// TODO Auto-generated method stub
        }

        /* (non-Javadoc)
         * @see java.awt.event.MouseListener#mouseEntered(java.awt.event.MouseEvent)
         */
        public void mouseEntered(MouseEvent e) {
            // TODO Auto-generated method stub
            
        }

        /* (non-Javadoc)
         * @see java.awt.event.MouseListener#mouseExited(java.awt.event.MouseEvent)
         */
        public void mouseExited(MouseEvent e) {
            // TODO Auto-generated method stub
            
        }

        /* (non-Javadoc)
         * @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent)
         */
        public void mousePressed(MouseEvent e) {
			xprev = e.getX();
			yprev = e.getY();
			e.consume();
		}

        /* (non-Javadoc)
         * @see java.awt.event.MouseListener#mouseReleased(java.awt.event.MouseEvent)
         */
        public void mouseReleased(MouseEvent e) {
            // TODO Auto-generated method stub
            
        }
        
        /*
		 * (non-Javadoc)
		 * 
		 * @see java.awt.event.MouseMotionListener#mouseDragged(java.awt.event.MouseEvent)
		 */
		public void mouseDragged(MouseEvent e) {
			int xMouse = e.getX();
			int yMouse = e.getY();

			xpos += xMouse - xprev;
			ypos += yMouse - yprev;

			xprev = xMouse;
			yprev = yMouse;
			ajustaXPosYPos();
			repaint();
			// System.out.println("posicao (" + xpos + ", " + ypos + ")");
			e.consume();

		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see java.awt.event.MouseMotionListener#mouseMoved(java.awt.event.MouseEvent)
		 */
		public void mouseMoved(MouseEvent arg0) {
			// TODO Auto-generated method stub
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see java.awt.event.MouseWheelListener#mouseWheelMoved(java.awt.event.MouseWheelEvent)
		 */
		public void mouseWheelMoved(MouseWheelEvent e) {
			if (e.getWheelRotation() > 0) {
				ampliar();
			} else if (e.getWheelRotation() < 0) {
				diminuir();
			}
			e.consume();
		}

		public void ampliar() {
			hmult *= 1.2;
			ajustaXPosYPos();
			repaint();
		}

		public void diminuir() {
			hmult /= 1.2;
			ajustaXPosYPos();
			repaint();
		}

		private void ajustaXPosYPos() {
			int xLimiteMax = imagem.getWidth(this) * hmult > getBounds().getWidth() ? 0 : (int) (getBounds().getWidth() - imagem.getWidth(this) * hmult);
			int xLimiteMin = imagem.getWidth(this) * hmult > getBounds().getWidth() ? (int) (getBounds().getWidth() - imagem.getWidth(this) * hmult) : 0;
			int yLimiteMax = imagem.getHeight(this) * hmult > getBounds().getHeight() ? 0 : (int) (getBounds().getHeight() - imagem.getHeight(this) * hmult);
			int yLimiteMin = imagem.getHeight(this) * hmult > getBounds().getHeight() ? (int) (getBounds().getHeight() - imagem.getHeight(this) * hmult) : 0;

			if (xpos > xLimiteMax)
				xpos = xLimiteMax;
			if (xpos < xLimiteMin)
				xpos = xLimiteMin;
			if (ypos > yLimiteMax)
				ypos = yLimiteMax;
			if (ypos < yLimiteMin)
				ypos = yLimiteMin;

		}
    }
    
}